<template>
    <el-form :model="registerUser" :rules="registerRules" ref="registerForm" label-width="100px" class="registerForm sign-up-form">
        <el-form-item label="用户名" prop="name">
            <el-input v-model="registerUser.name" placeholder="Enter Name..."></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="registerUser.email" placeholder="Enter Email..."></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input v-model="registerUser.password" type="password" placeholder="Enter Password..."></el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="password2">
            <el-input v-model="registerUser.password2" type="password" placeholder="Confirm Password..."></el-input>
        </el-form-item>
        <el-form-item label="选择身份">
            <el-select v-model="registerUser.role" placeholder="请选择身份">
                <el-option label="管理员" value="admin"></el-option>
                <el-option label="用户" value="user"></el-option>
                <el-option label="游客" value="visitor"></el-option>
            </el-select>
        </el-form-item>
        <el-form-item>
            <el-button @click="handleRegister" type="primary" class="submit-btn">注册</el-button>
        </el-form-item>
    </el-form>
</template>

<script lang="ts">
  import { getCurrentInstance } from "vue";
  import { useRouter } from "vue-router";

  export default {
    name: "registerForm",
    props: {
      registerUser: {
        type: Object,
        require: true
      },
      registerRules: {
        type: Object,
        require: true
      }
    },
    setup(props: any){
      // @ts-ignore
      const { ctx } = getCurrentInstance();  // getCurrentInstance获取当前组件的实例,ctx属性获取上下文
      const router = useRouter();
      const url = "/api/v1/auth/register";

      const handleRegister = () => {
        ctx.$refs.registerForm.validate((val: boolean) => {
          if (!val) return;
          ctx.$axios.post(url, props.registerUser).then((res: any) => {
            if (res.success) {
              ctx.$message.success("注册成功")
              router.push("/")
            } else {
              ctx.$message.error("注册失败")
            }

          }).catch(() => {
            ctx.$message.error("注册失败")
          })
        })
      }

      return { handleRegister }
    }
  }
</script>

<style scoped>
    /* 控制login & register显示 */
    .submit-btn {
        width: 100%;
    }
</style>